package com.gitee.hljdrl.lite.task;

import android.os.Handler;
import android.os.Looper;

import com.ffsky.logger.L;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class AndroidTask implements AppTask {

    ExecutorService fixedThreadPool = null;
    ExecutorService queueThreadPool = null;
    final String TAG = "AppTask";
    Handler uiHandler = new Handler(Looper.getMainLooper());

    public AndroidTask() {
        buildThreads();
    }

    private static final int CORE_POOL_SIZE = 4;
    private static final int MAX_POOL_SIZE = 8;
    private static final int KEEP_ALIVE_TIME = 90; // 80 seconds

    private synchronized void buildThreads() {
        fixedThreadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
                new AppTaskFactory());
        queueThreadPool = Executors.newFixedThreadPool(2, new AppTaskFactory());
    }

    @Override
    public void post(Runnable run) {
        L.i(TAG, "post->", run.getClass().getSimpleName());
        fixedThreadPool.execute(run);
    }

    @Override
    public void postQueue(Runnable run) {
        L.i(TAG, "postQueue->", run.getClass().getSimpleName());
        queueThreadPool.execute(run);
    }

    @Override
    public void ui(Runnable run) {
        L.i(TAG, "ui->", run.getClass().getSimpleName());
        uiHandler.post(run);
    }

    @Override
    public void uiTime(Runnable run, long time) {
        L.i(TAG, "uiTime->", run.getClass().getSimpleName(), ",time=", time);
        uiHandler.postDelayed(run, time);
    }

    @Override
    public void uiRemove(Runnable run) {
        L.i(TAG, "uiRemove->", run.getClass().getSimpleName());
        uiHandler.removeCallbacks(run);
    }

    @Override
    public void destroy() {
        if (queueThreadPool != null) {
            if (!queueThreadPool.isShutdown()) {
                queueThreadPool.shutdown();
                queueThreadPool = null;
            }
        }
        if (fixedThreadPool != null) {
            if (!fixedThreadPool.isShutdown()) {
                fixedThreadPool.shutdown();
                fixedThreadPool = null;
            }
        }
        if(uiHandler!=null){
            uiHandler.removeCallbacksAndMessages(null);
        }
    }
}
